﻿using System;
using System.Collections.Generic;
using System.Linq;
namespace WCF.Common.DAL
{
    public class RelationUserRoleDAL : BaseDAL
    {
        /// <summary>
        /// 获取表数据
        /// </summary>
        /// <returns>List</returns>
        public List<RelationUserRole> Gets()
        {
            var context = GetDataContext();
            var result = context.RelationUserRole.ToList();
            return result;
        }
        public List<string> GetByRoleID(string roldID)
        {
            var context = Gets();
            var ug = from relation in  Gets()
                     where relation.RoleID == roldID
                     select relation.UserID;
            if (ug.Count() == 0)
                return new List<string>();
            else
                return ug.ToList();
        }
        /// <summary>先删除所有数据，再增加数据</summary>
        /// <param name="roleID"></param>
        /// <param name="userIDs"></param>
        /// <returns></returns>
        public OperateResult Assign(string roleID, string[] userIDs)
        {
            try
            {
                var context = GetDataContext();
                var items = context.RelationUserRole.Where(p => p.RoleID == roleID);
                context.RelationUserRole.DeleteAllOnSubmit(items);
                foreach (var userID in userIDs)
                {
                    context.RelationUserRole.InsertOnSubmit(new RelationUserRole { RoleID = roleID, UserID = userID });
                }
                context.SubmitChanges();
            }
            catch (Exception ex)
            {
                return new OperateResult() { IsSuccess = false, Message = ex.Message };
            }
            return new OperateResult() { IsSuccess = true };
        }
    }
}